<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双端队列</title>
</head>

<body>
    <script>
        /* 
    使用ES6对象语法创建
*/
        class Deque {
            constructor() {
                this.count = 0; // 元素数量
                this.lowstCount = 0; // 队列顶部追踪器
                this.items = {}; // 存储器
            }
            // 向队首添加一个元素
            addFront(element) {
                if (this.isEmpty()) {
                    this.addBack(element);
                } else if (this.lowstCount > 0) {
                    this.items[--this.lowstCount] = element;
                } else {
                    for (let i = this.count; i > 0; i--) {
                        this.items[i] = this.count[i - 1];
                    }
                    this.count++;
                    this.lowstCount = 0;
                    this.items[0] = element;
                }

            }

            // 向队尾添加一个元素
            addBack(element) {
                this.items[this.count++] = element;
            }

            // 从队尾删除元素
            removeBack() {
                if (this.isEmpty()) return undefined;
                const res = this.items[this.lowstCount];
                delete this.items[this.lowstCount++];
                return res;
            }

            // 从队首删除元素
            removeFront() {
                if (this.isEmpty()) {
                    return undefined;
                } else {
                    let res = this.items[this.lowstCount];
                    this.count--;
                    for (let i = this.count; i > 0; i--) {
                        this.items[this.count - 1] = this.items[this.count];
                    }
                    delete this.items[this.lowstCount];
                    return res;
                }
            }

            // 查看队首元素
            peekFront() {
                if (this.isEmpty()) return undefined;
                return this.items[this.lowstCount];
            }

            // 查看队尾元素
            peekBack() {
                if (this.isEmpty()) return undefined;
                return this.items[this.count];
            }

            // 判断队列是否为空
            isEmpty() {
                return this.size() === 0;
            }

            // 返回长度大小
            size() {
                return this.count - this.lowstCount;
            }

            // 清空队列
            clear() {
                this.lowstCount = 0;
                this.count = 0;
                this.items = {};
            }

            // toString方法
            toString() {
                if (this.isEmpty()) return "";
                let res = "";
                for (let i = this.lowstCount; i < this.count; i++) {
                    res += this.items[i];
                }
                return res;
            }
        }
    </script>
</body>

</html>